<script setup lang="ts">
// 基础图表组件
import * as echarts from 'echarts'
import { nextTick, ref, watch } from 'vue'

interface EchartsVueProps {
	options: {
		type: object
		default: () => {}
	}
	[key: string]: any
}

// 不能直接从 defineProps 解构出来的变量不会生成响应式，Vue 3.5之后优化了此问题
const props = defineProps<EchartsVueProps>()
const echartsRef = ref<HTMLDivElement | null>(null)
const loading = ref(false)

// 加载图表插件
const initCharts = () => {
	// 获取echarts实例, 判断已经初始化过echarts实例
	let myEcharts = echarts.getInstanceByDom(echartsRef.value as HTMLDivElement)
	if (!myEcharts) {
		myEcharts = echarts.init(echartsRef.value as HTMLDivElement)
	}

	// 给个加载效果
	loading.value = true

	// 设置图表配置
	myEcharts.setOption(props.options ?? {}, true)
	setTimeout(() => {
		loading.value = false
	}, 1000)
}

watch(
	() => props.options,
	(val) => {
		// 监听props.options变化，重新渲染图表
		nextTick(() => {
			initCharts()
		})
	},
	{
		deep: true, // 深度监听，监听对象内部变化
		immediate: true // 立即执行一次
	}
)
</script>

<template>
	<a-spin :spinning="loading">
		<div ref="echartsRef" style="width: 800px; height: 500px"></div>
	</a-spin>
</template>

<style scoped></style>
